package com.lujianfei.productprice.ui.ShopDetail;

import com.lujianfei.productprice.ui.cart.CartEntity;
import com.lujianfei.productprice.ui.main.ShopEntity;
import com.lujianfei.productprice.ui.addProduct.ProductEntity;

import java.util.List;

public class ShopModel implements ShopContract.Model {

    private long shopId;
    @Override
    public List<ProductEntity> getData(long id) {
        shopId = id;
        List<ProductEntity> productEntities = ProductEntity.find(ProductEntity.class, "shopId=?", "" + id);
        if (null != productEntities) {
            for (ProductEntity productEntity :
                    productEntities) {
                ShopEntity shopEntity = ShopEntity.findById(ShopEntity.class, productEntity.getShopId());
                productEntity.setShopName(shopEntity.getShopName());
            }
        }
        return productEntities;
    }

    @Override
    public int getCartQuantity() {
        List<CartEntity> cartEntities = CartEntity.listAll(CartEntity.class);
        int totalQuantity = 0;
        if (null!=cartEntities) {
            for (CartEntity cartEntity:
                    cartEntities){
                totalQuantity += cartEntity.getQuantity();
            }
        }
        return totalQuantity;
    }

    @Override
    public void addToCart(ProductEntity data) {
        List<CartEntity> cartEntities = CartEntity.find(CartEntity.class, "productId=?", ""+data.getId());

        CartEntity cartEntity;
        if (null!=cartEntities && !cartEntities.isEmpty()){
            cartEntity = cartEntities.get(0);
            cartEntity.setQuantity(cartEntity.getQuantity()+1);
        }else{
            cartEntity = new CartEntity();
            cartEntity.setProductId(data.getId());
            cartEntity.setQuantity(1);
        }
        cartEntity.setShopId(data.getShopId());
        cartEntity.save();
    }

    @Override
    public void delete(ProductEntity productEntity) {
        productEntity.delete();
    }
}
